﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Processes.Orden;
using Model.Orden;
using System.Web.Security;
namespace Interfaces.Orden
{
    public partial class ModificarOrden : System.Web.UI.Page
    {

        Leaf tree;
        int number;
        List<int> numbers;
        DateTime date;
        GestorOrden gestorOrden;
        List<int> numbersModif;
        string NroReciv;
        DateTime dateReciv;
        public List<int> getNumero(string num)
        {
            char[] chars = { '.' };
            string[] words = num.Split(chars, StringSplitOptions.RemoveEmptyEntries);
            List<int> array = new List<int>();
            array.Add(1);
            for (int i = 0; i < words.Length; i++)
            {
                array.Add(Int32.Parse(words[i]));
            }
            if (array.Count == 2)
            {
                if (Session["number"] != null)
                    number = (int)Session["number"];
                number++;
                Session["number"] = number;

            }
            return array;
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            number = 1;
            numbers = new List<int>();
            numbersModif = new List<int>();
            tree = new Leaf();

            gestorOrden = new GestorOrden();
            if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "move")
            {
                numbersModif.Clear();
                numbersModif.Add(1);
                int index = ListBox1.SelectedIndex;
                if (index > 0)
                {
                    string content = ListBox1.SelectedItem.ToString();
                    char[] det = { ' ' };
                    string[] split = content.Split(det, StringSplitOptions.RemoveEmptyEntries);
                    string numberString = split[1];
                    content = "";
                    for (int i = 2; i < split.Length; i++)
                    {
                        content += split[i] + " ";
                    }
                    char[] det2 = { '.' };
                    split = numberString.Split(det2, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < split.Length; i++)
                    {
                        numbersModif.Add(int.Parse(split[i]));
                    }
                    textMod.Text = content;
                    Session["numbersMod"] = numbersModif;
                }

            }
            ListBox1.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(ListBox1, "move"));
            if (!IsPostBack)
            {
                NroReciv = Request.QueryString["Nro"];
                
                try
                {
                    if (NroReciv!=null&&!gestorOrden.EstaAprobada(NroReciv))
                    {
                        dateReciv = DateTime.Parse(Request.QueryString["Date"]);
                        Session["NroReciv"] = NroReciv;
                        Session["FechaReciv"] = dateReciv;
                        if (NroReciv != null && dateReciv != null)
                        {
                            List<Punto> puntosRec = gestorOrden.puntosDeNro(NroReciv);
                            dateTextBox.Text = dateReciv.ToShortDateString();
                            Session["FechaReciv"] = dateTextBox.Text;
                            for (int i = 0; i < puntosRec.Count; i++)
                            {
                                tree.insert(getNumero(puntosRec[i].NumeroPunto), tree, puntosRec[i].NombreDePunto);

                            }
                            printABB();
                            Session["tree"] = tree;
                        }
                    }
                    else
                    {
                        Response.Redirect("OrdenNoSePuedeModificar.aspx");
                    }
                }
                catch(Exception ex)
                {
                    Label1.Text = ex.Message;
                }
                

            }
            if (Session["tree"] != null)
            {
                tree = (Leaf)Session["tree"];
            }
            if (Session["number"] != null)
            {
                number = (int)Session["number"];
            }
            if (Session["date"] != null)
            {
                date = (DateTime)Session["date"];
            }
            if (Session["numbersMod"] != null)
            {
                numbersModif = (List<int>)Session["numbersMod"];
            }



        }

        private void insertListBox()
        {

        }
        private void insertNewPoint(bool point)
        {
            String text = textPoint.Text;
            numbers.Clear();
            tree.last = tree;
            if (!text.Equals(""))
            {
                numbers.Add(1);
                if (ListBox1.SelectedItem == null && point)
                {
                    numbers.Add(number);
                    if (numbers.Count == 2)
                        number++;
                    tree.insert(numbers, tree, text);
                    printABB();

                }
                else
                {
                    int index = ListBox1.SelectedIndex;
                    if (index != -1)
                    {
                        string[] split;
                        string[] split2 = { "" };
                        if (ListBox1.SelectedIndex != 0)
                        {
                            string content = ListBox1.SelectedItem.ToString();
                            char[] delimiter2 = { ' ' };
                            split = content.Split(delimiter2, StringSplitOptions.RemoveEmptyEntries);
                            string numberString = split[1];
                            char[] delimiter = { '.' };
                            split2 = numberString.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);


                            for (int i = 0; i < split2.Length - 1; i++)
                            {
                                numbers.Add(int.Parse(split2[i]));
                            }
                        }
                        if (point)
                        {
                            if (index > 0)
                                numbers.Add(int.Parse(split2[split2.Length - 1]) + 1);
                            else
                                numbers.Add(1);
                            if (numbers.Count == 2)
                                number++;
                            tree.insert(numbers, tree, text);
                            printABB();

                        }
                        else
                        {
                            if (index != 0)
                            {

                                numbers.Add(int.Parse(split2[split2.Length - 1]));
                                numbers.Add(1);
                                tree.insert(numbers, tree, text);
                                printABB();
                            }

                        }
                    }

                }

            }

            Session["tree"] = tree;
            Session["number"] = number;

        }
        protected void Point_Click(object sender, EventArgs e)
        {
            if (textPoint.Text != null)
            {
                Label1.Text = "";
                insertNewPoint(true);
                textPoint.Text = "";
            }
            else
            {
                Label1.Text = "No hay texto a introducir";
            }
        }
        public int calcularNroTabs(string num)
        {
            char[] delimiter = { '.' };
            string[] words = num.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
            return words.Length;
        }
        public void printABB()
        {
            ListBox1.Items.Clear();

            tree.allABB.Clear();
            tree.printAbb(tree, "");
            for (int i = 0; i < tree.allABB.Count; i++)
            {
                char[] delimiter = { ' ' };
                string[] words = tree.allABB[i].Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
                string tabs = "";
                if (words.Length > 0)
                {
                    int numTabs = calcularNroTabs(words[0]);

                    for (int j = 0; j < numTabs; j++)
                    {
                        tabs += "---";
                    }
                }

                ListBox1.Items.Add(tabs + tree.allABB[i]);
            }
        }
        protected void Delete_Click(object sender, EventArgs e)
        {
            String text = textPoint.Text;
            ListBox1.Items.Add(text);
        }

        protected void Button7_Click(object sender, EventArgs e)
        {
            ListBox1.Items.Add("HOla");
        }

        protected void AddPoint_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            String text = textPoint.Text;
            numbers.Clear();
            if (number != 1)
            {
                tree = (Leaf)Session["tree"];
                number = (int)Session["number"];
            }

            if (!text.Equals(""))
            {
                numbers.Add(1);
                if (ListBox1.SelectedItem == null)
                {
                    numbers.Add(number);
                    printABB();
                    number++;
                }
                else
                {
                    int index = ListBox1.SelectedIndex;
                    string content = ListBox1.SelectedItem.ToString();
                    string[] split = content.Split(' ');
                    string numberString = split[0];
                    split = numberString.Split('.');
                    for (int i = 0; i < split.Length - 1; i++)
                    {
                        numbers.Add(int.Parse(split[i]));
                    }
                    numbers.Add(int.Parse(split[split.Length - 1]) + 1);
                    numberString = "";
                    for (int i = 0; i < numbers.Count; i++)
                    {
                        numberString += numbers[i] + ".";
                    }
                    numberString += " ";
                    tree.insert(numbers, tree, text);
                    ListBox1.Items.Add(numberString + text);
                    //TODO ADD printABB
                    number++;
                }

            }

            Session["tree"] = tree;
            Session["number"] = number;
        }
        protected void subPoint_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            if (ListBox1.SelectedItem != null)
            {
                insertNewPoint(false);
                textPoint.Text = "";
                Label1.Text = "";
            }
            else
            {
                Label1.Text = "Tiene que seleccionar un punto para agregar un subpunto";
            }
        }
        private string DarContenido(List<Punto> puntosRecividos, string nro)
        {
            for (int i = 0; i < puntosRecividos.Count; i++)
            {
                if (puntosRecividos[i].NumeroPunto == nro)
                {
                    return puntosRecividos[i].Contenido;
                }
            }
            return "";
        }
        protected void Guardar_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            bool bandera = false;
            if (ListBox1.Items.Count != 0)
            {
                    if (dateTextBox.Text != "")
                    {
                        Order orden = new Order();
                        orden.Aprobada = false;
                        orden.Asociada = false;
                        orden.Fecha = DateTime.Parse(dateTextBox.Text + " 00:00:00");
                        orden.FechaUltimaModificacion = DateTime.Now;
                        orden.Nro = Session["NroReciv"].ToString();
                        List<Punto> puntos = new List<Punto>();
                        List<Punto> puntosRecuperados = gestorOrden.puntosDeNro(orden.Nro);
                        for (int i = 1; i < tree.allABB.Count; i++)
                        {
                            Punto punto = new Punto();
                            char[] det = { ' ' };
                            string[] token = tree.allABB[i].Split(det, StringSplitOptions.RemoveEmptyEntries);
                            for (int j = 1; j < token.Length; j++)
                            {
                                punto.NombreDePunto += token[j] + " ";
                            }
                            punto.Nro = orden.Nro;
                            punto.NumeroPunto = token[0];
                            puntos.Add(punto);
                        }
                        for (int i = 0; i < puntos.Count; i++)
                        {
                            puntos[i].Contenido = DarContenido(puntosRecuperados, puntos[i].NumeroPunto);
                        }
                            try
                            {
                                NroReciv = Session["NroReciv"].ToString();
                                dateReciv = gestorOrden.FechaDeNumero(NroReciv);
                            }
                            catch (Exception ex)
                            {

                                throw ex;
                            }
                        if (dateReciv.ToShortDateString().Equals(dateTextBox.Text) || !gestorOrden.ExisteOrdenEnEsaFecha(orden.Fecha))
                        {
                            if (puntos.Count > 0)
                            {
                                if (Session["NroReciv"]!=null && gestorOrden.SetOrden(orden.Fecha,orden.Nro,puntos))
                                {
                                    bandera = true;
                                }

                                else
                                {
                                    Label1.Text = "No se pudo crear la orden, pudieron ocurrir los siguientes errores:</br> -El servidor se encuentra dehabilitado<br> -Hubo un problema con la conexión";
                                }
                            }
                            else
                            {
                                Label1.Text = "La orden se encuentra vacía, llene los datos por favor";
                            }
                        }
                        else
                        {
                            Label1.Text = "No se pudo crear la orden, porque ya existe una orden para esta fecha";
                        }
                    }
                    else
                    {
                        Label1.ForeColor = System.Drawing.Color.Red;
                        Label1.Text = "Debe llenar la fecha para poder completar la creación";
                    }
                }
            if (bandera)
                Response.Redirect("OrdenExitosa.aspx");
        }

        protected void Mofi_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            if (textMod.Text != "" && numbersModif.Count != 0)
            {
                tree.modificar(numbersModif, tree, textMod.Text);
                printABB();
            }
            else
            {
                Label1.ForeColor = System.Drawing.Color.Red;
                Label1.Text = "Tiene que seleccionar un punto para modificarlo haciendo doble click sobre él";
            }
            textMod.Text = "";
        }

        protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (Session["BuscarMaster"] != null)
            {

                this.MasterPageFile = (string)Session["BuscarMaster"];
            }
        }
        protected void Eliminar_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            tree.last = tree;
            if (textMod.Text != "" && numbersModif.Count != 1)
            {
                if (numbersModif.Count == 2)
                {
                    number--;
                    Session["number"] = number;
                }

                tree.eliminar(numbersModif, tree);
                printABB();

            }
            else
            {
                Label1.ForeColor = System.Drawing.Color.Red;
                Label1.Text = "Tiene que seleccionar un punto para eliminarlo, haciendo doble click sobre él";
            }
            textMod.Text = "";
        }
}
}